import React, { useState, useEffect } from 'react';
import { Card, Button, Radio, Spin, message, Result, Typography, Divider, Space } from 'antd';
import { useParams, useNavigate } from 'react-router-dom';
import { materialOrderService } from '../../services/materialOrderService';
import { CheckCircleOutlined, LoadingOutlined } from '@ant-design/icons';

const { Title, Text, Paragraph } = Typography;

const MaterialPayment = () => {
  const { orderNumber } = useParams();
  const navigate = useNavigate();
  
  const [loading, setLoading] = useState(true);
  const [paymentLoading, setPaymentLoading] = useState(false);
  const [order, setOrder] = useState(null);
  const [paymentMethod, setPaymentMethod] = useState('alipay');
  const [paymentResult, setPaymentResult] = useState(null);
  const [paymentStatus, setPaymentStatus] = useState('pending');
  const [pollingInterval, setPollingInterval] = useState(null);

  // 获取订单详情
  useEffect(() => {
    const fetchOrderDetails = async () => {
      try {
        setLoading(true);
        const data = await materialOrderService.getOrderDetails(orderNumber);
        setOrder(data);
      } catch (error) {
        console.error('获取订单详情失败:', error);
        message.error('获取订单详情失败: ' + (error.message || '未知错误'));
      } finally {
        setLoading(false);
      }
    };

    fetchOrderDetails();
  }, [orderNumber]);

  // 清理轮询
  useEffect(() => {
    return () => {
      if (pollingInterval) {
        clearInterval(pollingInterval);
      }
    };
  }, [pollingInterval]);

  // 处理支付方式变更
  const handlePaymentMethodChange = (e) => {
    setPaymentMethod(e.target.value);
  };

  // 创建支付订单
  const handleCreatePayment = async () => {
    try {
      setPaymentLoading(true);
      const result = await materialOrderService.createPayment(orderNumber, paymentMethod);
      setPaymentResult(result);
      
      // 如果是扫码支付，开始轮询支付状态
      if (result.qrCodeUrl || result.paymentUrl) {
        startPollingPaymentStatus(result.paymentId);
      }
      
    } catch (error) {
      console.error('创建支付订单失败:', error);
      message.error('创建支付订单失败: ' + (error.message || '未知错误'));
    } finally {
      setPaymentLoading(false);
    }
  };

  // 轮询支付状态
  const startPollingPaymentStatus = (paymentId) => {
    const interval = setInterval(async () => {
      try {
        const statusResult = await materialOrderService.queryPaymentStatus(paymentId);
        
        if (statusResult.status === 'success') {
          setPaymentStatus('success');
          clearInterval(interval);
          message.success('支付成功！');
          
          // 更新订单状态
          const updatedOrder = await materialOrderService.getOrderDetails(orderNumber);
          setOrder(updatedOrder);
        } else if (statusResult.status === 'failed') {
          setPaymentStatus('failed');
          clearInterval(interval);
          message.error('支付失败，请重试');
        }
      } catch (error) {
        console.error('查询支付状态失败:', error);
      }
    }, 3000); // 每3秒查询一次
    
    setPollingInterval(interval);
  };

  // 查看订单详情
  const viewOrderDetails = () => {
    navigate(`/material/order/${orderNumber}`);
  };

  // 返回材料列表
  const backToMaterials = () => {
    navigate('/materials');
  };

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
        <p>加载订单信息...</p>
      </div>
    );
  }

  if (!order) {
    return (
      <Result
        status="error"
        title="订单不存在"
        subTitle="无法找到该订单信息，请检查订单号是否正确"
        extra={
          <Button type="primary" onClick={backToMaterials}>
            返回材料列表
          </Button>
        }
      />
    );
  }

  // 如果订单已支付
  if (order.status === 'paid' || paymentStatus === 'success') {
    return (
      <Result
        icon={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
        status="success"
        title="支付成功"
        subTitle={`订单号: ${orderNumber}`}
        extra={[
          <Button type="primary" key="details" onClick={viewOrderDetails}>
            查看订单详情
          </Button>,
          <Button key="materials" onClick={backToMaterials}>
            返回材料列表
          </Button>
        ]}
      />
    );
  }

  return (
    <Card className="payment-container">
      <Title level={3}>订单支付</Title>
      <Divider />
      
      <div className="order-info">
        <Paragraph>
          <Text strong>订单号:</Text> {order.orderNumber}
        </Paragraph>
        <Paragraph>
          <Text strong>材料:</Text> {order.material?.title}
        </Paragraph>
        <Paragraph>
          <Text strong>价格:</Text> ¥{order.totalAmount}
        </Paragraph>
      </div>
      
      <Divider />
      
      {!paymentResult ? (
        <>
          <Title level={4}>选择支付方式</Title>
          <Radio.Group onChange={handlePaymentMethodChange} value={paymentMethod}>
            <Space direction="vertical">
              <Radio value="alipay">支付宝</Radio>
              <Radio value="wechat">微信支付</Radio>
            </Space>
          </Radio.Group>
          
          <div className="payment-action" style={{ marginTop: '20px' }}>
            <Button 
              type="primary" 
              onClick={handleCreatePayment} 
              loading={paymentLoading}
              block
            >
              立即支付
            </Button>
          </div>
        </>
      ) : (
        <div className="payment-qrcode">
          <Title level={4}>请扫码支付</Title>
          
          {paymentResult.qrCodeUrl && (
            <div className="qrcode-container">
              <img src={paymentResult.qrCodeUrl} alt="支付二维码" />
            </div>
          )}
          
          {paymentResult.paymentUrl && (
            <div className="payment-link">
              <Button type="primary" href={paymentResult.paymentUrl} target="_blank">
                点击跳转到支付页面
              </Button>
            </div>
          )}
          
          <div className="payment-status" style={{ marginTop: '20px' }}>
            <Spin indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />} />
            <Text style={{ marginLeft: '10px' }}>等待支付完成...</Text>
          </div>
        </div>
      )}
    </Card>
  );
};

export default MaterialPayment;